"use client";

import { logApi } from '@/constants';
import { get, post, del } from '@/util/api';

// 系统日志项接口
export interface SystemLog {
  id: number;
  level: 'debug' | 'info' | 'warn' | 'error' | 'fatal';
  module: string;
  action: string;
  message: string;
  userId?: number;
  username?: string;
  ip?: string;
  userAgent?: string;
  params?: Record<string, any>;
  stack?: string;
  createdAt: string;
}

// 系统日志列表响应接口
export interface SystemLogListResponse {
  data: SystemLog[];
  total: number;
  page: number;
  pageSize: number;
}

// 日志统计数据接口
export interface LogStats {
  totalCount: number;
  levelDistribution: Array<{
    level: string;
    count: number;
    percentage: number;
  }>;
  moduleDistribution: Array<{
    module: string;
    count: number;
    percentage: number;
  }>;
  dailyTrend: Array<{
    date: string;
    count: number;
    errorCount: number;
  }>;
  recentErrors: SystemLog[];
}

// 日志查询过滤器接口
export interface LogFilter {
  level?: string | string[];
  module?: string;
  action?: string;
  userId?: number;
  keyword?: string;
  ip?: string;
  startDate?: string;
  endDate?: string;
}

/**
 * 系统日志管理服务类
 * 封装所有系统日志相关的API调用
 */
class SystemLogService {
  /**
   * 获取系统日志列表
   * @param params 查询参数
   * @returns Promise<SystemLogListResponse>
   */
  /**
   * 获取管理员操作日志
   */
  async getAdminOperations(params?: {
    page?: number;
    pageSize?: number;
    operationType?: string;
    adminId?: number;
    startDate?: string;
    endDate?: string;
    searchText?: string;
  }): Promise<SystemLogListResponse> {
    try {
      const response = await get(logApi.ADMIN_OPERATIONS, { params });
      return (response.data || response) as unknown as SystemLogListResponse;
    } catch (error) {
      console.error('获取管理员操作日志失败:', error);
      throw error;
    }
  }

  /**
   * 获取登录日志
   */
  async getLoginLogs(params?: {
    page?: number;
    pageSize?: number;
    loginResult?: number;
    adminId?: number;
    startDate?: string;
    endDate?: string;
    searchText?: string;
  }): Promise<SystemLogListResponse> {
    try {
      const response = await get(logApi.LOGIN_LOGS, { params });
      return (response.data || response) as unknown as SystemLogListResponse;
    } catch (error) {
      console.error('获取登录日志失败:', error);
      throw error;
    }
  }

  /**
   * 获取安全事件
   */
  async getSecurityEvents(params?: {
    page?: number;
    pageSize?: number;
    securityLevel?: number;
    isRead?: number;
    startDate?: string;
    endDate?: string;
    searchText?: string;
  }): Promise<SystemLogListResponse> {
    try {
      const response = await get(logApi.SECURITY_EVENTS, { params });
      return (response.data || response) as unknown as SystemLogListResponse;
    } catch (error) {
      console.error('获取安全事件失败:', error);
      throw error;
    }
  }

  /**
   * 标记安全事件为已读
   */
  async markSecurityEventAsRead(id: number): Promise<void> {
    try {
      await get(logApi.MARK_SECURITY_READ(id));
    } catch (error) {
      console.error(`标记安全事件已读失败 (ID: ${id}):`, error);
      throw error;
    }
  }

  /**
   * 解决安全事件
   */
  async resolveSecurityEvent(id: number, resolution: string): Promise<void> {
    try {
      await post(logApi.RESOLVE_SECURITY(id), { resolution });
    } catch (error) {
      console.error(`解决安全事件失败 (ID: ${id}):`, error);
      throw error;
    }
  }

  /**
   * 获取日志统计信息
   */
  async getStatistics(): Promise<LogStats> {
    try {
      const response = await get(logApi.STATISTICS);
      return (response.data || response) as unknown as LogStats;
    } catch (error) {
      console.error('获取日志统计信息失败:', error);
      throw error;
    }
  }

  /**
   * 清理过期日志
   */
  async cleanupOldLogs(): Promise<{ message: string }> {
    try {
      const response = await post(logApi.CLEANUP);  
      return (response.data || response) as unknown as { message: string };
    } catch (error) {
      console.error('清理过期日志失败:', error);
      throw error;
    }
  }

  /**
   * 获取系统日志列表（保留以兼容旧代码）
   * @deprecated 使用 getAdminOperations, getLoginLogs, getSecurityEvents 替代
   */
  async getSystemLogList(params?: {
    page?: number;
    pageSize?: number;
    level?: string | string[];
    module?: string;
    action?: string;
    userId?: number;
    keyword?: string;
    ip?: string;
    startDate?: string;
    endDate?: string;
    orderBy?: 'createdAt';
    orderDirection?: 'asc' | 'desc';
  }): Promise<SystemLogListResponse> {
    try {
      const response = await get(logApi.LIST, { params });
      return (response.data || response) as unknown as SystemLogListResponse;
    } catch (error) {
      console.error('获取系统日志列表失败:', error);
      throw error;
    }
  }

  /**
   * 获取日志详情
   * @param id 日志ID
   * @returns Promise<SystemLog>
   */
  async getLogDetail(id: number): Promise<SystemLog> {
    try {
      const response = await get(logApi.DETAIL(id));
      return (response.data || response) as unknown as SystemLog;
    } catch (error) {
      console.error(`获取日志详情失败 (ID: ${id}):`, error);
      throw error;
    }
  }

  /**
   * 导出系统日志
   * @param format 导出格式
   * @param filter 过滤条件
   * @returns Promise<Blob>
   */
  async exportLogs(format: 'json' | 'csv' | 'excel' = 'json', filter?: LogFilter){
    try {
      console.log('导出系统日志参数:', { format, filter });

    } catch (error) {
      console.error('导出系统日志失败:', error);
      throw error;
    }
  }

  /**
   * 删除日志
   * @param id 日志ID
   */
  async deleteLog(id: number): Promise<void> {
    try {
      await del(logApi.DELETE(id));   
    } catch (error) {
      console.error(`删除日志失败 (ID: ${id}):`, error);
      throw error;
    }
  }

  /**
   * 批量删除日志
   * @param ids 日志ID数组
   * @returns Promise<{ success: number; failed: number }>
   */
  async batchDeleteLogs(ids: number[]){
    try {
      // const response = await del(logApi.BATCH_DELETE, { ids });
      // return response.data || response;
    } catch (error) {
      console.error('批量删除日志失败:', error);
      throw error;
    }
  }

  /**
   * 清空日志
   * @param filter 过滤条件
   * @returns Promise<{ deleted: number }>
   */
  async clearLogs(filter?: LogFilter) {
    try {
      // const response = await del(logApi.CLEAR, filter);
      // return response.data || response;
    } catch (error) {
      console.error('清空日志失败:', error);
      throw error;
    }
  }

  /**
   * 获取日志统计数据
   * @param params 查询参数
   * @returns Promise<LogStats>
   */
  async getLogStats(params?: {
    startDate?: string;
    endDate?: string;
    limit?: number;
  }){
    try {
      // const response = await get(logApi.STATS, params);
      // return response.data || response;
    } catch (error) {
      console.error('获取日志统计数据失败:', error);
      throw error;
    }
  }

  /**
   * 获取日志模块列表
   * @returns Promise<string[]>
   */
  async getLogModules(){
    try {
      // const response = await get(logApi.MODULES);
      // return response.data || response;
    } catch (error) {
      console.error('获取日志模块列表失败:', error);
      throw error;
    }
  }

  /**
   * 搜索日志
   * @param keyword 搜索关键词
   * @param params 搜索参数
   * @returns Promise<SystemLogListResponse>
   */
  async searchLogs(keyword: string, params?: {
    page?: number;
    pageSize?: number;
    level?: string | string[];
    startDate?: string;
    endDate?: string;
  }): Promise<SystemLogListResponse> {
    try {
      const response ={};// await get(logApi.SEARCH, { keyword, ...params });
      return ( response ) as unknown as SystemLogListResponse;
    } catch (error) {
      console.error('搜索日志失败:', error);
      throw error;
    }
  }

  /**
   * 手动记录日志
   * @param logData 日志数据
   * @returns Promise<SystemLog>
   */
  async recordLog(logData: {
    level: 'debug' | 'info' | 'warn' | 'error' | 'fatal';
    module: string;
    action: string;
    message: string;
    params?: Record<string, any>;
  }) {
    try {
      // const response = await post(logApi.RECORD, logData);
      // return response.data || response;
    } catch (error) {
      console.error('记录日志失败:', error);
      throw error;
    }
  }
}

// 导出系统日志服务实例
export const systemLogService = new SystemLogService();
export default systemLogService;